package com.vrsys.domain.session;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

import com.vrsys.domain.LineItem;
import com.vrsys.domain.Product;

@Component("cart")
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Cart implements Serializable{
    private static final long serialVersionUID = 5170549741501012019L;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public static MathContext mc = new MathContext(4);
    private BigDecimal amount = new BigDecimal(0d,mc);
    private Map<Integer, LineItem> lineItems = new LinkedHashMap<Integer, LineItem>();

    public List<LineItem> getProducts() {
        List<LineItem> products = new LinkedList<LineItem>();
        products.addAll(this.lineItems.values());
        return products;
    }

    public LineItem getLineItem(int lineId) {
        return this.lineItems.get(lineId);
    }

    public boolean checkProduct(int pId) {
        if(this.lineItems.containsKey(pId))
            return true;
        return false;
    }

    /*
     * @return 0 - newly added; 1 cannot re-add 
     */
    public byte putToCart(Product product) {
        if(!this.lineItems.containsKey(product.getProductId())) {
            this.amount = this.amount.add(product.getUnitPrice(),mc);
            LineItem lineItem = new LineItem();
            lineItem.setProduct(product);
            this.lineItems.put(product.getProductId(), lineItem);
            return 0x0;
        } else
            return 0x1;
//        logger.debug("" + this.amount.doubleValue());
        
    }

    public void removeProduct(int pId) {
        Product product = this.lineItems.remove(pId).getProduct();
        this.amount = this.amount.subtract(product.getUnitPrice());
    }

    public int getCartSize() {
        return this.lineItems.keySet().size();
    }

    public BigDecimal getAmount() {
        return this.amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public void cleanCart() {
        this.amount = new BigDecimal(0);
        this.lineItems = new LinkedHashMap<Integer, LineItem>();
    }
}
